package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
)

func generateMsToken(length int) string {
	baseStr := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	token := make([]byte, length)
	for i := range token {
		token[i] = baseStr[i%len(baseStr)]
	}
	return string(token)
}

// GetRoomID 从直播间地址获取 roomID
func (w *WebSocketApp) GetRoomID() string {
	if w.roomID != "" {
		return w.roomID
	}

	url := w.LiveURL + w.LiveID
	headers := map[string]string{
		"User-Agent": w.UserAgent,
		"cookie":     fmt.Sprintf("ttwid=%s; msToken=%s; __ac_nonce=0123407cc00a9e438deb4", w.ttwid, generateMsToken(107)),
	}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatalf("创建请求失败: %v", err)
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 发送请求并处理响应
	resp, err := w.httpClient.Do(req)
	if err != nil {
		log.Printf("请求直播间 URL 错误: %v", err)
		return ""
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Printf("请求失败，状态码: %d", resp.StatusCode)
		return ""
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("读取响应错误: %v", err)
		return ""
	}

	// 使用正则表达式提取 roomId
	re := regexp.MustCompile(`roomId\\":\\"(\d+)\\"`)
	match := re.FindStringSubmatch(string(body))
	if match == nil || len(match) < 2 {
		log.Println("【X】没有找到 roomId 匹配项")
		return ""
	}

	w.roomID = match[1]
	return w.roomID
}
